﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace XamlKru.Math3D
{
    public class PlaneModel3D
    {
        public IList<Point3D> Vertices
        {
            get;
            private set;
        }

        public IList<Int32> Indices
        {
            get;
            private set;
        }

        public IList<Point> TexturePositions
        {
            get;
            private set;
        }

        public PlaneModel3D(Int32 xTileCount, Int32 yTileCount)
        {
            if (xTileCount<1) 
                throw new ArgumentOutOfRangeException("xTileCount");

            if (yTileCount<1) 
                throw new ArgumentOutOfRangeException("yTileCount");

            Vertices = new List<Point3D>();
            Indices = new List<Int32>();
            TexturePositions = new List<Point>();

            Double dx = 1d / xTileCount;
            Double dy = 1d / yTileCount;

            Int32 xCount = xTileCount + 1;
            Int32 yCount = yTileCount + 1;

            for (Int32 ty = 0; ty < yCount; ty++)
            {
                for (Int32 tx = 0; tx < xCount; tx++)
                {
                    Double x = dx * tx, y = dy * ty;
                    Vertices.Add(new Point3D(-1d + 2d * x, -1 + 2d * y, 0));
                    TexturePositions.Add(new Point(x, y));

                    if ((tx > 0) && (ty > 0))
                    {
                        Int32 indexA = (ty - 1) * xCount + (tx - 1);
                        Int32 indexB = indexA + 1;
                        Int32 indexC = indexA + xCount;
                        Int32 indexD = indexC + 1;

                        Indices.Add(indexA); Indices.Add(indexB); Indices.Add(indexC);
                        Indices.Add(indexB); Indices.Add(indexD); Indices.Add(indexC);
                    }
                }
            }            
        }

        public PointCollection GetTexturePositions(Int32 triangleIndex)
        {
            Int32 indexA = Indices[triangleIndex * 3];
            Int32 indexB = Indices[triangleIndex * 3 + 1];
            Int32 indexC = Indices[triangleIndex * 3 + 2];

            return new PointCollection
            {
                TexturePositions[indexA],
                TexturePositions[indexB],
                TexturePositions[indexC],
            };
        }
    }
}
